package service

import (
	"errors"

	"gitee.com/cyanbleeze/go-image-management/internal/model"
	"gitee.com/cyanbleeze/go-image-management/pkg/app"
)

type CategoryRequest struct {
	ID uint `json:"id,omitempty" binding:"required,min=1"`
}

type CreateCategoryRequest struct {
	Name string `json:"name,omitempty" binding:"required,min=2"`
	Desc string `json:"desc,omitempty" binding:"omitempty,min=2"`
}

type UpdateCategoryRequest struct {
	ID   uint   `json:"id,omitempty" binding:"required,min=1"`
	Name string `json:"name,omitempty" binding:"required,min=2,max=30"`
	Desc string `json:"desc,omitempty" binding:"omitempty,min=2,max=255"`
}

type DeleteCategoryRequest struct {
	ID uint `json:"id" binding:"required,min=1"`
}

func (svc *Service) CreateCategory(params *CreateCategoryRequest) error {
	userID, exist := svc.ctx.Get("userID")
	if !exist {
		return errors.New("登录用户信息不存在")
	}
	return svc.dao.CreateCategory(
		params.Name,
		params.Desc,
		userID.(uint),
	)
}

func (svc *Service) UpdateCategory(params *UpdateCategoryRequest) error {
	userID, exist := svc.ctx.Get("userID")
	if !exist {
		return errors.New("登录用户信息不存在")
	}
	_, err := svc.dao.GetCategory(
		params.ID,
		userID.(uint),
	)
	if err != nil {
		return errors.New("分类不存在")
	}
	return svc.dao.UpdateCategory(
		params.ID,
		params.Name,
		params.Desc,
	)
}

func (svc *Service) DeleteCategory(params *DeleteCategoryRequest) error {
	userID, exist := svc.ctx.Get("userID")
	if !exist {
		return errors.New("登录用户信息不存在")
	}
	category, err := svc.dao.GetCategory(params.ID, userID.(uint))
	if err != nil {
		return err
	}
	if category.Type == 1 {
		return errors.New("默认图片分类不允许删除")
	}
	_, err = svc.dao.GetCategory(
		params.ID,
		userID.(uint),
	)
	if err != nil {
		return errors.New("分类不存在")
	}
	return svc.dao.DeleteCategory(params.ID)
}

func (svc *Service) GetCategoryList(page *app.Pager) ([]*model.Category, error) {
	userID, exist := svc.ctx.Get("userID")
	if !exist {
		return nil, errors.New("登录用户信息不存在")
	}
	return svc.dao.GetCategoryList(userID.(uint), page.Page, page.PageSize)
}
